import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login } from '@/api/login'
import { getServerCart} from "@/api/cart"

const useUserStore = defineStore('user', () => {

    // state 数据
    const token = ref<string>('')
    const userid = ref<string>('')
   
    // action 方法
    const loginAction = async(user: LoginUser) => {
      try {
        //网络请求 ，登录
            const result = await login(user)
            // console.log("登录：",result)
            //修改状态数据
            token.value = result.token 
            userid.value = result.userid
            //登陆成功,将服务端当前用户的购物车数据同步到本地数据
            const cart = await getServerCart(result.userid)
            console.log("同步购物的数据：",cart)
            return true 
 
        }catch(error ){   
            console.error("异常",error)
            return false
        }  
    }
    return{
        token,  
        userid,
        loginAction,

    }

}) 
 export default useUserStore 